<%--
  Created by IntelliJ IDEA.
  User: zhangxiaokang
  Date: 2025/10/30
  Time: 下午2:36
  To change this template use File | Settings | File Templates.
--%>

<link rel="icon" href="${pageContext.request.contextPath}/images/favicon.ico" type="image/x-icon">
<%@ page contentType="text/html;" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车 - 梦幻蛋糕坊</title>
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/style.css">
</head>
<body>
<div class="header">
    <h1>购物车</h1>
    <p>您的甜蜜选择</p>
</div>

<div class="cart-container">
    <c:choose>
        <c:when test="${cart == null || cart.amount == 0}">
            <div class="empty-cart">
                <h3>购物车是空的</h3>
                <p>您还没有添加任何商品到购物车</p>
                <a href="index.jsp" class="continue-shopping">继续购物</a>
            </div>
        </c:when>
        <c:otherwise>
            <div class="cart-items-container">
                <table class="cart-table">
                    <thead>
                        <tr>
                            <th>商品</th>
                            <th>单价</th>
                            <th>数量</th>
                            <th>小计</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <c:forEach var="item" items="${cart.items}">
                            <tr>
                                <td>
                                    <div class="cart-item-info">
                                        <img src="${item.cake.imageUrl}" alt="${item.cake.name}" class="cart-item-image">
                                        <span>${item.cake.name}</span>
                                    </div>
                                </td>
                                <td>¥${item.cake.price}</td>

                                <%--数量控制--%>
                                <td class="quantity-control">
                                    <button class="quantity-btn minus" data-id="${item.cake.id}" onclick="decreaseQuantity(this)">-</button>
                                    <span class="quantity-value">${item.quantity}</span>
                                    <button class="quantity-btn plus" data-id="${item.cake.id}" onclick="increaseQuantity(this)">+</button>
                                </td>



                                <td>¥${item.subTotal}</td>
                                <td>
                                    <a href="cartServlet?opt=remove&id=${item.cake.id}" class="remove-item">删除</a>
                                </td>
                            </tr>
                        </c:forEach>
                    </tbody>
                </table>
                <div class="cart-summary">
                    <div class="total-price">
                        总计: <span class="price">¥${cart.totalPrice}</span>
                    </div>
                    <div class="cart-actions">
                        <a href="index.jsp" class="continue-shopping">继续购物</a>
                        <button class="checkout-btn">结算</button>
                    </div>
                </div>
            </div>
        </c:otherwise>
    </c:choose>
</div>

<%--JavaScript部分，用于处理数量增加减少和总价更新--%>
<script>
    function increaseQuantity(btn) {
        const id = btn.getAttribute('data-id');
        const quantitySpan = btn.previousElementSibling;
        let currentQty = parseInt(quantitySpan.textContent);
        currentQty++;
        quantitySpan.textContent = currentQty;

        // 更新小计
        const price = parseFloat(btn.parentNode.parentNode.cells[1].textContent.replace('¥', ''));
        const subTotalCell = btn.parentNode.parentNode.cells[3];
        subTotalCell.textContent = '¥' + (price * currentQty).toFixed(1);

        // 更新总价
        updateTotalPrice();

        // 发送请求到服务器更新购物车
        updateCart(id, currentQty);
    }

    function decreaseQuantity(btn) {
        const id = btn.getAttribute('data-id');
        const quantitySpan = btn.nextElementSibling;
        let currentQty = parseInt(quantitySpan.textContent);

        if (currentQty === 1) {
            if (confirm("是否删除该商品？")) {
                // 删除商品
                window.location.href = "cartServlet?opt=remove&id=" + id;
            }
        } else {
            currentQty--;
            quantitySpan.textContent = currentQty;

            // 更新小计
            const price = parseFloat(btn.parentNode.parentNode.cells[1].textContent.replace('¥', ''));
            const subTotalCell = btn.parentNode.parentNode.cells[3];
            subTotalCell.textContent = '¥' + (price * currentQty).toFixed(1);

            // 更新总价
            updateTotalPrice();

            // 发送请求到服务器更新购物车
            updateCart(id, currentQty);
        }
    }

    function updateCart(id, num) {
        // 向服务器发送异步请求更新购物车
        fetch("cartServlet?opt=update&id=" + id + "&num=" + num, {
            method: "GET"
        }).then(response => {
            if (!response.ok) throw new Error("网络错误");
        }).catch(err => {
            alert("更新失败：" + err.message);
        });
    }

    function updateTotalPrice() {
        let total = 0;
        document.querySelectorAll('.cart-table tbody tr').forEach(tr => {
            const subTotalText = tr.cells[3].textContent.replace('¥', '');
            total += parseFloat(subTotalText);
        });
        document.querySelector('.price').textContent = '¥' + total.toFixed(1);
    }

    // 页面加载完成后初始化总价
    window.onload = function () {
        updateTotalPrice();
    };
</script>

</body>
</html>

